import { loginApi, addInfo, userInfoId } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'
import router from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, data) {
      state.token = data
      setToken(data)
    },
    // 设置用户信息
    setUserInfo(state, data) {
      state.userInfo = data
    },
    clearAll(state) {
      state.token = null
      state.userInfo = {}
    }
  },
  actions: {
    // 获得用户信息
    async getUserInfo(ctx) {
      const res = await addInfo()
      const res1 = await userInfoId(res.userId)
      console.log(res)
      console.log(res1)
      ctx.commit('setUserInfo', { ...res, ...res1 })
    },
    // 登录
    async login(ctx, data) {
      const res = await loginApi(data)
      console.log(res)
      ctx.commit('setToken', res)
      // token 持久化
      setToken(res)
    },
    logout(ctx) {
      ctx.commit('clearAll')
      router.push('/login')
    }
  }
}
